package cn.cdeden.aiqa.service.impl;

import cn.cdeden.aiqa.domain.WikiApp;
import cn.cdeden.aiqa.domain.WikiAppPerm;
import cn.cdeden.aiqa.domain.bo.AssignPermissionsRequest;
import cn.cdeden.aiqa.domain.vo.WikiAppCount;
import cn.cdeden.aiqa.mapper.WikiAppMapper;
import cn.cdeden.aiqa.mapper.WikiAppPermMapper;
import cn.cdeden.aiqa.service.WikiAppService;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class WikiAppServiceImpl implements WikiAppService {

    private final WikiAppMapper wikiAppMapper;
    private final WikiAppPermMapper wikiAppPermMapper;

    @Override
    public WikiApp createWikiApp(WikiApp wikiApp) {
        wikiAppMapper.insert(wikiApp);
        return wikiApp;
    }

    @Override
    public void updateWikiApp(WikiApp wikiApp) {
        wikiAppMapper.updateById(wikiApp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWikiApps(List<Long> ids) {
        wikiAppMapper.deleteBatchIds(ids);
        wikiAppPermMapper.delete(new LambdaQueryWrapper<WikiAppPerm>()
            .in(WikiAppPerm::getAppId, ids));
    }

    @Override
    public TableDataInfo<WikiApp> getAllWikiApps(String appName, PageQuery pageQuery) {
        LambdaQueryWrapper<WikiApp> lqw = buildQueryWrapper(appName);
        Page<WikiApp> result = wikiAppMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<WikiAppPerm> getAppPermissions(Long appId) {
        return wikiAppPermMapper.selectList(new LambdaQueryWrapper<WikiAppPerm>()
                .eq(WikiAppPerm::getAppId, appId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignPermissions(Long appId, AssignPermissionsRequest request) {
        // 删除已有的权限
        wikiAppPermMapper.delete(new LambdaQueryWrapper<WikiAppPerm>().eq(WikiAppPerm::getAppId, appId));

        // 添加新的用户权限
        if (request.getUserIds() != null && !request.getUserIds().isEmpty() && request.getUserNames() != null && !request.getUserNames().isEmpty()) {
            for (int i = 0; i < request.getUserIds().size(); i++) {
                WikiAppPerm perm = new WikiAppPerm();
                perm.setAppId(appId);
                perm.setUserId(request.getUserIds().get(i));
                perm.setUserName(request.getUserNames().get(i));
                wikiAppPermMapper.insert(perm);
            }
        }

        // 添加新的部门权限
        if (request.getDeptIds() != null && !request.getDeptIds().isEmpty() && request.getDeptNames() != null && !request.getDeptNames().isEmpty()) {
            for (int i = 0; i < request.getDeptIds().size(); i++) {
                WikiAppPerm perm = new WikiAppPerm();
                perm.setAppId(appId);
                perm.setDeptId(request.getDeptIds().get(i));
                perm.setDeptName(request.getDeptNames().get(i));
                wikiAppPermMapper.insert(perm);
            }
        }

    }

    @Override
    public List<WikiApp> getAuthorizedApps(Long deptId, Long userId,String wikiType) {
        return wikiAppMapper.getAuthorizedApps(deptId, userId,wikiType);
    }

    @Override
    public WikiApp getgetAuthorizedAppByDataSetId(String dataSetId){
        List<WikiApp> wikiApps = wikiAppMapper.selectList(new LambdaQueryWrapper<WikiApp>()
            .like(WikiApp::getWikiIds, dataSetId));
        if (wikiApps.size() > 0) {
            return wikiApps.get(0);
        }else{
            return new WikiApp();
        }
    }

    @Override
    public boolean crCount(Long appId) {
        WikiApp wikiApp = wikiAppMapper.selectById(appId);

        Long rCount = wikiApp.getRCount();
        wikiApp.setRCount(++rCount);

        return wikiAppMapper.updateById(wikiApp) > 0;
    }

    @Override
    public WikiAppCount crCountInfo() {
        // 查询所有 WikiApp 数据
        List<WikiApp> wikiApps = wikiAppMapper.selectList(new QueryWrapper<>());

        // 初始化返回对象
        WikiAppCount wikiAppCount = new WikiAppCount();
        List<String> appNames = new ArrayList<>();
        List<Long> counts = new ArrayList<>();
        List<Integer> rates = new ArrayList<>();

        // 计算总使用次数
        long totalCount = wikiApps.stream()
            .mapToLong(WikiApp::getRCount)
            .sum();

        // 填充数据
        for (WikiApp app : wikiApps) {
            appNames.add(app.getAppName());
            long count = app.getRCount();
            counts.add(count);
            // 计算使用率，避免除以 0 的情况
            int rate = totalCount > 0 ? (int) ((count * 100) / totalCount) : 0;
            rates.add(rate);
        }

        // 设置返回对象的属性
        wikiAppCount.setAppNames(appNames);
        wikiAppCount.setCounts(counts);
        wikiAppCount.setRates(rates);

        return wikiAppCount;
    }

    private LambdaQueryWrapper<WikiApp> buildQueryWrapper(String appName) {
        LambdaQueryWrapper<WikiApp> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(appName), WikiApp::getAppName, appName);
        return lqw;
    }

}
